"""
@author: wtf
@file: qa.py
@time: 2024/5/8 16:39
@desc: View controllers related to Q&A
"""
import json
import os.path
from datetime import datetime
from flask import render_template, request, Blueprint, g, redirect, url_for
from qiniu import put_file

import config
import models
from decorators import login_required
from exts import db, q
from models import PublicQuestionModel
from blueprints import forms

bp = Blueprint("qa", __name__, url_prefix="/")


@bp.route("/")
def index():
    page = int(request.args.get("page", 1))  # 默认是1
    # questions = PublicQuestionModel.query.order_by(PublicQuestionModel.join_time.desc()).all()
    pagination = PublicQuestionModel.query.order_by(PublicQuestionModel.join_time.desc()).paginate(page=page,
                                                                                                   per_page=5)  # 默认第一页 per_page=10表示每页10条数据
    # print("是否有下一页", pagination.has_next)
    # print("是否有上一页", pagination.has_prev)
    # print("总的记录条数", pagination.total)
    # print("对象数", pagination.items)
    # print("上一页是", pagination.prev_num)
    # print("下一页是:", pagination.next_num)
    # print(pagination.pages)  总页数
    # print(pagination.page)  当前页码
    # for question in pagination.items:
    #     print(question.question)
    return render_template("index.html", pagination=pagination)


@bp.route("/public/question", methods=["GET", "POST"])
@login_required
def public_question():
    if request.method == "GET":
        return render_template("public_question.html")
    else:
        form = forms.PublicQuestionForms(request.form)
        if form.validate():
            # validate success , insert question
            question = form.question.data
            content = form.content.data
            # author_id = g.get("user").id
            question = PublicQuestionModel(question=question, content=content, author=g.get("user"))
            db.session.add(question)
            db.session.commit()
            return redirect(url_for("qa.index"))
        else:
            print(form.errors)
            return json.dumps(form.errors, indent=4, ensure_ascii=False)  # indent=4 缩进空格数


@bp.route("/qa/detail/<qa_id>")
def question_detail(qa_id):
    question = PublicQuestionModel.query.get(qa_id)
    return render_template("detail.html", question=question)


@bp.route("/public/answer", methods=["POST"])
@login_required
def public_answer():
    form = forms.PublicAnswerForm(request.form)
    if form.validate():
        question_id = form.question_id.data
        content = form.content.data
        user = g.get("user")
        answer = models.PublicAnswerModel(content=content, question_id=question_id, user=user)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for("qa.question_detail", qa_id=question_id))
    else:
        return redirect(url_for("qa.question_detail", qa_id=request.form.get("question_id")))


@bp.route("/search")
def question_search():
    page = int(request.args.get("page", 1))
    keywords = request.args.get("keywords")
    pagination = PublicQuestionModel.query.filter(
        PublicQuestionModel.question.contains(keywords)).order_by(PublicQuestionModel.join_time.desc()).paginate(
        page=page, per_page=5)
    return render_template("index.html", pagination=pagination, search_btn=1, mykeywords=keywords)


@bp.route("/test2")
def test2():
    print(os.path.dirname(__file__))
    print(datetime.now().timestamp())
    print(os.path.isfile("./static/photos/test.jpg"))
    print(" ===============================================================")
    # -*- coding: utf-8 -*-
    # flake8: noqa
    #
    # bucket_name = 'wtfwt9876'
    # # 上传后保存的文件名
    # key = 'my-python-logo.png'
    #
    # # 生成上传 Token，可以指定过期时间等
    # token = q.upload_token(bucket_name, key, 3600)
    # # 要上传文件的本地路径
    # localfile = os.path.join(config.PHOTO_DIR, "test.jpg")
    # ret, info = put_file(token, key, localfile, version='v2')
    # print(info)
    # print(info.status_code)

    return render_template("show_photos.html")


@bp.route("/user")
def user2():
    return render_template("user.html", user=g.get("user"))
